package com.grep.extra.factory.utils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.grep.base.util.FileUtil;

public class JsoupUtil {
	static Logger logger = LoggerFactory.getLogger(JsoupUtil.class);
	
	private Document doc;
	
	private Charset charset = null ;
	
	private JsoupUtil(){}
	 

	public Charset getCharset() {
		return charset;
	}


	/**
	 * 远程URL的构造函数
	 * @param url
	 */
	public JsoupUtil(String url){
		try {
			doc = Jsoup.connect(url).get(); 
			parseCodeType() ;
		} catch (IOException e) {
			logger.error("[JsoupUtil] connect Exception {} . ",url ) ;
			e.printStackTrace() ;
		}
	}
	/**
	 * 从远程html中获取html自己的编码。
	 */
	private void parseCodeType (){
		Elements elements  = doc.select("meta") ;
		String content = null ;
		for(Element elet : elements){
			content = elet.attr("content");
			if(content.indexOf("charset")>-1){
				String set = content.split("charset")[1].trim() ;
				if(set.indexOf("=")>-1){
					set = set.substring(1).trim() ;
				}
				if(set.indexOf(";")>-1){
					set = set.replace(";","").trim();
				}
				charset = Charset.availableCharsets().get(set);
				if(charset== null){
					logger.info(" charset({}) is not available! " , set);
				}
				break;
			}
		}
	}
	/**
	 * 本地文件的构造函数
	 * @param filePath
	 * @param baseUrl
	 * @param codeType
	 */
	public JsoupUtil(String filePath ,String baseUrl,Charset charset){
		try {
			if(charset == null){
				charset = Charset.defaultCharset() ;
			}
			File input = new File(filePath); 
			doc = Jsoup.parse(input,charset.toString(),baseUrl); 
			
			//从html中获取文件编码
			parseCodeType() ;
		} catch (IOException e) {
			logger.error("[JsoupUtil] connect Exception {} . ",filePath ) ;
			e.printStackTrace() ;
		}
	}
	public String getAtrr(String path){
		return null ;
	}
	
	private boolean writeFileByCharset(String filename){
		if(filename !=null && doc!=null){
			return FileUtil.writeFileByCharset(filename, charset.toString(), doc.toString()) ;
		}else {
			logger.error("[JsoupUtil] write file failed ! filename is :{}",filename) ;
			return false ;
		}
		
	}
	//根据文件编码写文件
	public boolean writeContentFile(String filename){
		if(charset != null){
			return writeFileByCharset(filename);
		}else{
			if(filename !=null && doc!=null){
				return FileUtil.writeFileUseStrFW(filename, doc.toString()) ;
			}else {
				logger.error("[JsoupUtil] write file failed ! filename is :{}",filename) ;
				return false ;
			}
		}
	}
	/**
	 * 获取html链接元素的href值
	 * @param path
	 * @return
	 */
	public List<String> getURLSByPath(String path){
		List<String> result = new ArrayList<String>();
		Elements elements = doc.select(path);
		String url = "http://anotherbug.blog.chinajavaworld.com/entry/4545/0/";
		Pattern p = Pattern.compile(".*?\\.(com|cn|net|org|biz|info|cc|tv)",Pattern.CASE_INSENSITIVE);
		Matcher matcher = p.matcher(doc.baseUri());
		matcher.find();
		String domain = matcher.group();
		for(Element elet : elements){
			String hr = elet.attr("href");
			if(hr.startsWith("/")){
				hr = domain + hr;
			}
			result.add(hr);
		}
		return result;
	}
	/**
	 * 获取html元素文本值
	 * @param path
	 * @return
	 */
	public List<String> getTextByPath(String path){
		List<String> result = new ArrayList<String>();
		Elements elements = doc.select(path);
		
		for(Element elet : elements){
			result.add(elet.text());
		}
		return result;
	}
	
	public String getHtmlText(){
		return doc.html();
	}
	
	public static String getDomain(String pattern,String url){
		Pattern p = Pattern.compile(pattern,Pattern.CASE_INSENSITIVE);
		Matcher matcher = p.matcher(url);
		matcher.find();
		String domain = matcher.group();
		return domain;
	}
	public static void main (String [] args){
//		JsoupUtil jsouputil = new JsoupUtil("http://www.7k7k.com/tag/134/");
//		List<String> result = jsouputil.getURLSByPath("DIV > .lazyload-part > li > a[href~=/flash/.*?htm]");
//		for(String str : result){
//			System.out.println(str) ;
//		}
//	String pattern = "(?<=http://|\\.)[^.]*?\\.(com|cn|net|org|biz|info|cc|tv)";
	String pattern = ".*?\\.(com|cn|net|org|biz|info|cc|tv)";
	String url = "http://www.7k7k.com/tag/134/";
	System.out.print(JsoupUtil.getDomain(pattern, url));
	}
	
}
